package com.junlaninfo.service;

import com.junlaninfo.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * Created by 辉 on 2020/7/24.
 * 开多一个线程执行记日志、发邮件、发邮件，这中法方法简单但是不要用于工作环境
 */
@RestController
public class LoginService2{
    private static final Logger log = LoggerFactory.getLogger(LoginService2.class);

    @GetMapping("/login2")
    public String login(UserEntity userEntity) throws ExecutionException, InterruptedException {
        //1、先查询登录是否成功
        UserEntity userEntity1 = dbLogin(userEntity);
        if (userEntity1 == null) {
            return "登录名或者密码不对";
        }

        //开启一个线程专门处理写日志、发短息、发邮件
        new Thread(new Runnable() {
            @Override
            public void run() {
                loginLog(userEntity);
                sendSms(userEntity);
                sendEmail(userEntity);
            }
        }).start();
        return "登录成功";
    }

    public void run(UserEntity userEntity) {
        //2、写日志
        loginLog(userEntity);
        //3、发短信
        sendSms(userEntity);
        //4、发邮件
        sendEmail(userEntity);

    }

    private UserEntity dbLogin(UserEntity userEntity) {
        log.info(">>>1.正在查询数据库登陆<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
        return userEntity;
    }

    private void loginLog(UserEntity userEntity) {
        log.info(">>>2.异步开始写登陆的日志<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
//        int i = 1 / 0;
    }

    private void sendSms(UserEntity userEntity) {
        log.info(">>>3.异步开始发送短信<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
    }

    private void sendEmail(UserEntity userEntity) {
        log.info(">>>4.异步开始发送邮件<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
    }
}
